package china.z.loquacity.common.utils;

import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;

/**
 * 非对称加密
 *
 * @author zengyz
 * @date 2018-04-20
 */
public class RSAUtils {

    public RSAUtils() {
    }

    public static void main(String[] args) throws InvalidKeySpecException, NoSuchAlgorithmException {
        HashMap<String, String> randomKey = RSAUtils.getRandomKey();
        System.out.println("公钥："+randomKey.get("publicKey"));
        System.out.println("私钥："+randomKey.get("privateKey"));
    }

    /**
     * 随机获取公钥私钥
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static HashMap<String, String> getRandomKey() throws NoSuchAlgorithmException, InvalidKeySpecException {

        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        /**
         * 生成大小1024
         */
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        /**
         * 获取公钥
         */
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        /**
         * 获取私钥
         */
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        HashMap<String, String> keyMap = new HashMap<String, String>();

        /**
         * 获取公钥Base64编码
         */
        keyMap.put("publicKey", Base64.encode(publicKey.getEncoded()));

        /**
         * 获取密钥Base64编码
         */
        keyMap.put("privateKey", Base64.encode(privateKey.getEncoded()));
        return keyMap;
    }

}
